//
// Created by wsl on 2024/3/8.
//

#include "LinkStack.h"

DataStructure_Warning_Unused
static LinkStack_Node LinkStack_CreateNode(T e, size_t dataSize) {
	if (NULL == e)
		return NULL;

	//创建节点
	LinkStack_Node newNode = (LinkStack_Node) DataStructure_AllocT(LinkStack_N);
	if (NULL == newNode) {
		//内存分配失败，调用溢出处理函数
		DataStructure_Overflow_Handler();
		return NULL;                //兜底
	}

	//创建数据域
	T data = DataStructure_AllocT(dataSize);
	if (NULL == data) {
		DataStructure_MemoryFree(newNode);
		DataStructure_Overflow_Handler();
		return NULL;
	}

	//为数据域赋值
	DataStructure_MemoryCpy(data, e, dataSize);

	//初始化节点
	newNode->data = data;
	newNode->next = NULL;

	return newNode;
}

DataStructure_Warning_Unused
LinkStack LinkStack_create(size_t dataSize) {

	//创建栈
	LinkStack tempLinkStack = (LinkStack) DataStructure_AllocT(LinkSTK);
	if (NULL == tempLinkStack) {
		DataStructure_Overflow_Handler();
		return NULL;
	}

	//初始化各项属性
	tempLinkStack->head = NULL;    //指向头节点
	tempLinkStack->length = 0;
	tempLinkStack->dataSize = dataSize;

	//返回对象
	return tempLinkStack;
}

DataStructure_Warning_Unused
Status LinkStack_isEmpty(LinkStack list) {
	if (NULL == list)
		return FALSE;

	return list->length <= 0 ? TRUE : FALSE;
}

DataStructure_Warning_Unused
Status LinkStack_top(LinkStack list, T e)
{
	if (NULL == list || NULL == e || NULL == list->head)
		return FALSE;

	DataStructure_MemoryCpy(e, list->head->data, list->dataSize);

	return TRUE;
}

DataStructure_Warning_Unused
Status LinkStack_push(LinkStack list, T e) {

	if (NULL == list || NULL == e)
		return FALSE;

	//创建节点
	LinkStack_Node temp = LinkStack_CreateNode(e, list->dataSize);
	if (NULL == temp)
		return FALSE;

	if (NULL == list->head) //无节点，直接挂载
	{
		list->head = temp;
	}
	else
	{
		//头链接
		temp->next = list->head;
		list->head = temp;
	}

	list->length++;

	return TRUE;
}

DataStructure_Warning_Unused
Status LinkStack_pop(LinkStack list, T buf) {
	if (NULL == list || NULL == buf || NULL == list->head)
		return FALSE;

	//记录释放的节点
	LinkStack_Node temp = list->head;

	list->head = temp->next;

	DataStructure_MemoryCpy(buf, temp->data, list->dataSize);

	//释放首元节点的数据域
	DataStructure_MemoryFree(temp->data);
	//释放旧首元节点
	DataStructure_MemoryFree(temp);

	//更新数量
	list->length--;

	return TRUE;
}

DataStructure_Warning_Unused
Status LinkStack_clear(LinkStack list) {
	if (NULL == list)
		return FALSE;

	//记录释放的节点
	LinkStack_Node curNode = list->head;
	LinkStack_Node temp;

	while (curNode)
	{
		temp = curNode;

		curNode = curNode->next;

		//释放首元节点的数据域
		DataStructure_MemoryFree(temp->data);
		//释放旧首元节点
		DataStructure_MemoryFree(temp);

		//更新数量
		list->length--;
	}

	list->head = NULL;

	return TRUE;
}

DataStructure_Warning_Unused
Status LinkStack_destroy(LinkStack *list) {
	if (NULL == list || NULL == *list)
		return FALSE;

	//释放所有节点
	if (LinkStack_isEmpty(*list) == FALSE)
		LinkStack_clear(*list);

	//释放链表对象
	DataStructure_MemoryFree(*list);

	//置空
	*list = NULL;

	return TRUE;

}
